<template>
  <a-spin :spinning="spinning">
    <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <div class="tip">甲方信息</div>
      <a-row :gutter="16" type="flex">
        <a-col :span="24">
          <a-form-item label="甲方（出租方）" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
            <a-input
              v-decorator="['UnitName', { rules: [{ required: true, message: '请输入甲方（出租方）' }] }]"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="通讯地址" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
            <a-input
              v-decorator="['UnitAddress', { rules: [{ required: true, message: '请输入通讯地址' }] }]"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话">
            <a-input v-decorator="['UnitPhone', { rules: [{ required: true, message: '请输入联系电话' }] }]"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="法定代表人">
            <a-input
              v-decorator="['LegalRepresentative', { initialValue: '' }]"
              placeholder="请输入法定代表人"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8" />
        <a-col :span="8">
          <a-form-item label="委托代理人">
            <a-input v-decorator="['Agent', { initialValue: '' }]" placeholder="请输入委托代理人"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="经办人">
            <a-input v-decorator="['Operator', { initialValue: '' }]" placeholder="请输入经办人"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话">
            <a-input v-decorator="['LessorNumber', { initialValue: '' }]" placeholder="请输入联系电话"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <div class="tip">乙方信息</div>
      <a-row :gutter="16" type="flex">
        <a-col :span="8">
          <a-form-item label="乙方（承租方）">
            <a-input
              v-decorator="['Name', { rules: [{ required: true, message: '请输入乙方（承租方）' }] }]"
              placeholder="请输入乙方（承租方）"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="公民身份证号">
            <a-input
              v-decorator="['IDCard', { rules: [{ required: true, message: '请输入公民身份证号' }] }]"
              placeholder="请输入公民身份证号"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8" />
        <a-col :span="24">
          <a-form-item label="户籍所在地" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
            <a-input
              v-decorator="['CensusRegAddress', { rules: [{ required: true, message: '请输入户籍所在地' }] }]"
              placeholder="请输入户籍所在地"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话">
            <a-input
              v-decorator="['Tel', { rules: [{ required: true, message: '请输入联系电话' }] }]"
              placeholder="请输入联系电话"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="紧急联系人">
            <a-input v-decorator="['UrgentName', { initialValue: '' }]" placeholder="请输入紧急联系人"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话">
            <a-input v-decorator="['UrgentTel', { initialValue: '' }]" placeholder="请输入紧急联系电话"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="委托代理人">
            <a-input v-decorator="['TenantryAgent', { initialValue: '' }]" placeholder="请输入委托代理人"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="经办人">
            <a-input v-decorator="['TenantryOperator', { initialValue: '' }]" placeholder="请输入经办人"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话">
            <a-input v-decorator="['TenantryPhone', { initialValue: '' }]" placeholder="请输入联系电话"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <div class="tip">房屋信息</div>
      <a-row type="flex">
        <a-col :span="24">
          <a-form-item label="房屋信息" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
            <a-textarea
              v-decorator="['EAddress', { rules: [{ required: true, message: '请输入房屋信息' }] }]"
              placeholder="请输入房屋信息"
            ></a-textarea>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="房屋类型">
            <a-radio-group
              v-decorator="['HighLevel', { rules: [{ required: true, message: '请输入房屋类型' }] }]"
              :options="[
                { value: '高层', label: '高层' },
                { value: '多层', label: '多层' },
              ]"
            ></a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="房屋建筑面积">
            <a-input-number
              :formatter="(value) => `${value}㎡`"
              v-decorator="['BuilderArea', { rules: [{ required: true, message: '请输入房屋建筑面积' }] }]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8" />
        <a-col :span="8">
          <a-form-item label="租赁期限">
            <a-input-number
              :precision="0"
              :formatter="(value) => `${value}月`"
              v-decorator="['Years', { rules: [{ required: true, message: '请输入租赁期限' }] }]"
              @change="handleChange($event, 'Years')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="起租日期">
            <a-date-picker
              value-format="YYYY-MM-DD"
              v-decorator="['StartDate', { rules: [{ required: true, message: '请选择起租日期' }] }]"
              placeholder="请选择起租日期"
              @change="handleChange($event, 'StartDate')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="止租日期">
            <a-input
              v-decorator="['EndDate', { rules: [{ required: true, message: '请输入租赁期限并选择起租日期' }] }]"
              placeholder="止租日期自动计算"
            ></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <div class="tip">租金标准</div>
      <a-row :gutter="16" type="flex">
        <a-col :span="8">
          <a-form-item label="租金标准">
            <a-select
              v-decorator="['rentStandard', { rules: [{ required: true, message: '请选择租金标准' }] }]"
              showSearch
              allowClear
              optionFilterProp="label"
              @change="handleChange($event, 'rentStandard')"
              placeholder="请选择租金标准"
            >
              <a-select-option
                v-for="item in rentStandardOptions"
                :key="item.ID"
                :value="item.ID"
                :label="item.STANDARDNAME"
                >{{ item.STANDARDNAME }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="每平米租金">
            <a-input-number
              :formatter="(value) => `${value}元/㎡`"
              v-decorator="['RentMM', { initialValue: 0, rules: [{ required: true, message: '请选择租金标准' }] }]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="每月租金合计">
            <a-input-number
              :formatter="(value) => `￥${value}`"
              v-decorator="['RentMonth', { initialValue: 0, rules: [{ required: true, message: '请选择租金标准' }] }]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="减免类型">
            <a-select
              v-decorator="['ReductionType']"
              allowClear
              :options="[
                { value: 1, label: '低保' },
                { value: 2, label: '低收入' },
              ]"
              @change="handleChange($event, 'ReductionType')"
              placeholder="请选择减免类型"
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="租金减免政策">
            <a-select
              allowClear
              v-decorator="[
                'rentReduction',
                {
                  initialValue: [],
                  // rules: [{ required: !$isEmpty(form.getFieldValue('ReductionType')), message: '请选择租金减免政策' }],
                },
              ]"
              @change="handleChange($event, 'rentReduction')"
              placeholder="请选择租金减免政策"
            >
              <!-- :mode="$isEmpty(form.getFieldValue('ReductionType')) ? 'multiple' : 'default'" -->
              <a-select-option v-for="item in rentReductionOptions" :key="item.ID" :value="item.REDUCTIONPROPORTION">{{
                item.STANDARDNAME
              }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="保证金(押金)">
            <a-input-number :formatter="(value) => `￥${value}`" v-decorator="['Margin', { initialValue: '' }]" />
          </a-form-item>
        </a-col>
      </a-row>
      <div>
        <div class="tip">解除本合同的条件</div>
        <a-form-item label="其他情形" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
          <a-textarea
            v-decorator="['OtherCases', { initialValue: '' }]"
            placeholder="请输入解除本合同的条件"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          ></a-textarea>
        </a-form-item>
      </div>
      <div>
        <div class="tip">条款信息</div>
        <a-form-item label="补充条款" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
          <span slot="extra" class="text-warning"
            >温馨提示：如需添加多个附件, 格式为：x：《xxxxxxxx》, x：《xxxxxxxx》</span
          >
          <a-textarea
            v-decorator="['Content', { initialValue: '' }]"
            placeholder="请输入补充条款"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          ></a-textarea>
        </a-form-item>
        <a-form-item label="签订日期" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
          <a-date-picker
            value-format="YYYY-MM-DD"
            v-decorator="['SignDate', { rules: [{ required: true, message: '请选择签订日期' }] }]"
            placeholder="请选择签订日期"
            style="width: auto"
          />
        </a-form-item>
      </div>
    </a-form>
    <div class="text-center">
      <y-button @click="handleClose">关闭</y-button>
      <y-button type="primary" :loading="isSubmiting" @click="handleSubmit">{{
        isSubmiting ? '提交中' : '提交'
      }}</y-button>
    </div>
  </a-spin>
</template>

<script>
import {
  getRentManageList,
  getRentReductStandardManageList,
  getSignContractMode,
  postContract,
  getContractDetail,
} from '@/api/followUpManagement'
import moment from 'moment'
import pick from 'lodash.pick'
import BigNumber from 'bignumber.js'

export default {
  props: {
    type: {
      type: String,
      default: 'add',
    },
    proposerID: {
      require: true,
      type: [String, Number],
      default: '',
    },
    pactClass: {
      require: true,
      type: String,
      default: '新签合同',
    },
    contractID: {
      type: [String, Number],
      default: '',
    },
  },
  inject: ['handleClose'],
  watch: {
    proposerID(n) {
      if (n) {
        this.fetchData()
      }
    },
  },
  mounted() {
    this.fetchData()
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'signContract' }),
      isSubmiting: false,
      spinning: false,
      rentStandard: '',
      rentStandardOptions: [],
      rentReductionOptions: [],
      signContractInfo: {},
    }
  },
  methods: {
    fetchData() {
      if (!this.proposerID) return
      const getRentStandardOptions = getRentManageList()
      const getRentReductionOptions = getRentReductStandardManageList({
        LB: 1,
      })
      const axiosArr = [getRentStandardOptions, getRentReductionOptions]
      if (this.type === 'continue') {
        // 续签
        const $getContractDetail = getContractDetail({
          ID: this.contractID,
        })
        axiosArr.unshift($getContractDetail)
      } else if (this.type === 'add') {
        const getSignContractInfo = getSignContractMode({ ID: this.proposerID })
        axiosArr.unshift(getSignContractInfo)
      }
      this.spinning = true
      Promise.all(axiosArr)
        .then((res) => {
          if (this.type === 'add') {
            // 新签
            this.signContractInfo = res[0]
            this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(res[0], [
                  'UnitName',
                  'UnitAddress',
                  'UnitPhone',
                  'Name',
                  'IDCard',
                  'CensusRegAddress',
                  'Tel',
                  'EAddress',
                  'BuilderArea',
                ])
              )
            })
          } else if (this.type === 'continue') {
            this.signContractInfo = res[0]
            this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(res[0], [
                  'UnitName',
                  'UnitAddress',
                  'UnitPhone',
                  'LegalRepresentative',
                  'Agent',
                  'Operator',
                  'LessorNumber',
                  'Name',
                  'IDCard',
                  'CensusRegAddress',
                  'Tel',
                  'UrgentName',
                  'UrgentTel',
                  'TenantryAgent',
                  'TenantryOperator',
                  'TenantryPhone',
                  'EAddress',
                  'HighLevel',
                  'BuilderArea',
                  'ReductionType',
                  'Margin',
                  'OtherCases',
                  'Content',
                ])
              )
              this.form.setFieldsValue({
                SignDate: moment(res[0].SignDate, 'YYYY-MM-DD'),
              })
            })
            // 续签
          }
          this.rentStandardOptions = res[1]
          this.rentReductionOptions = res[2]
        })
        .finally(() => {
          this.spinning = false
        })
    },
    handleChange(e, type) {
      switch (type) {
        case 'rentStandard':
          if (this.$isEmpty(e)) {
            this.form.setFieldsValue({
              RentMM: 0,
              RentMonth: 0,
            })
            return
          }
          const { BASICRENTSTANDARD } = this.rentStandardOptions.find((item) => item.ID === e)
          const area = this.form.getFieldValue('BuilderArea')
          this.form.setFieldsValue({
            RentMM: BASICRENTSTANDARD,
            RentMonth: new BigNumber(area).multipliedBy(BASICRENTSTANDARD).toNumber(),
          })
          this.$nextTick(() => {
            const rentReduction = this.form.getFieldValue('rentReduction')
            if (!this.$isEmpty(rentReduction)) {
              this.handleChange(rentReduction, 'rentReduction')
            }
            const ReductionType = this.form.getFieldValue('ReductionType')
            if (!this.$isEmpty(ReductionType)) {
              this.handleChange(ReductionType, 'ReductionType')
            }
          })
          break
        case 'rentReduction':
          if (this.$isEmpty(e)) {
            const rentStandard = this.form.getFieldValue('rentStandard')
            this.handleChange(rentStandard, 'rentStandard')
          } else {
            const area = this.form.getFieldValue('BuilderArea')
            const RentMM = this.form.getFieldValue('RentMM')
            const MPFZJ = this.rentStandardOptions.find(
              (item) => item.ID === this.form.getFieldValue('rentStandard')
            ).BASICRENTSTANDARD // 当前选择的每平方租金
            // if (this.$isEmpty(this.form.getFieldValue('ReductionType'))) {
            //   e.forEach((number) => {
            //     this.form.setFieldsValue({
            //       RentMonth: new BigNumber(area)
            //         .multipliedBy(RentMM)
            //         .multipliedBy(number)
            //         .multipliedBy(0.01)
            //         .toNumber(),
            //     })
            //   })
            // }
            if (!this.form.getFieldValue('ReductionType')) {
              this.form.setFieldsValue({
                RentMonth: new BigNumber(area).multipliedBy(RentMM).multipliedBy(e).multipliedBy(0.01).toNumber(),
              })
            } else if (this.form.getFieldValue('ReductionType') === 1) {
              this.form.setFieldsValue({
                RentMonth: new BigNumber(area).multipliedBy(e).multipliedBy(0.01).toNumber(),
              })
            } else if (this.form.getFieldValue('ReductionType') === 2) {
              const nowRentMonth = new BigNumber(area).multipliedBy(MPFZJ).div(2).dp(2).toNumber() // 当前租金合计除2保留位小数
              this.form.setFieldsValue({
                RentMonth: new BigNumber(nowRentMonth).multipliedBy(e).multipliedBy(0.01).toNumber(),
              })
            }
            // }
          }
          break
        case 'Years':
          const date = this.form.getFieldValue('StartDate')
          this.setEndDate(e, date)
          break
        case 'StartDate':
          const month = this.form.getFieldValue('Years')
          this.setEndDate(month, e)
          break
        case 'ReductionType': // 减免类型 (低保、低收入)
          // 选择减免类型时清空减免政策
          this.form.setFieldsValue({
            rentReduction: [],
          })
          if (this.$isEmpty(e)) {
            const rentStandard = this.form.getFieldValue('rentStandard')
            this.handleChange(rentStandard, 'rentStandard')
          } else {
            const BuilderArea = this.form.getFieldValue('BuilderArea')
            const MPFZJ = this.rentStandardOptions.find(
              (item) => item.ID === this.form.getFieldValue('rentStandard')
            ).BASICRENTSTANDARD // 当前选择的每平方租金
            if (e === 1) {
              this.form.setFieldsValue({
                RentMonth: BuilderArea,
              })
            } else if (e === 2) {
              this.form.setFieldsValue({
                RentMonth: new BigNumber(BuilderArea).multipliedBy(MPFZJ).div(2).dp(2).toNumber(), // 当前租金合计除2保留位小数
              })
            }
          }
          break
        default:
          break
      }
    },
    setEndDate(month, date) {
      if (!this.$isEmpty(month) && !this.$isEmpty(date)) {
        const endDate = moment(date).add(month, 'months').subtract(1, 'days')
        this.form.setFieldsValue({
          EndDate: endDate.format('YYYY-MM-DD'),
        })
      } else {
        this.form.setFieldsValue({
          EndDate: '',
        })
      }
    },
    handleSubmit() {
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.isSubmiting = true
          let data = null
          delete values.rentStandard
          delete values.rentReduction
          if (this.type === 'add') {
            const { ApplyNo, ESites } = this.signContractInfo
            data = Object.assign({}, values, {
              ApplyNo,
              ESites,
              ApplyID: this.proposerID,
              ReductionType: values.ReductionType || '',
              Unit: '',
              AddPeopleID: this.$store.getters.userid,
              pactClass: this.pactClass,
            })
          } else {
            const { ApplyNo, ESites, ApplyID, Unit, ReductionType } = this.signContractInfo
            data = Object.assign({}, values, {
              ApplyNo,
              ESites,
              ApplyID,
              ReductionType: values.ReductionType || ReductionType,
              Unit,
              AddPeopleID: this.$store.getters.userid,
              pactClass: this.pactClass,
            })
          }
          postContract({
            State: this.type === 'add' ? 'add' : 'renewal',
            UserID: this.$store.getters.userid,
            enpm: data,
          })
            .then((res) => {
              const { PactNoGUID, code } = res[0]
              if (code === '200') {
                this.$message.success('合同提交成功')
                this.$emit('submit', PactNoGUID)
              } else {
                this.$message.error('合同提交失败，请重试')
              }
            })
            .finally(() => {
              this.isSubmiting = false
            })
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-input-number,
.ant-calendar-picker {
  width: 100%;
}
</style>
